# 定义应用的路由和视图函数

# 蓝图是 Flask 中的组织代码的方式。
# 它允许你将相关的视图函数、模板和静态文件组织在一起，并且可以在多个应用中重用。

from flask import Blueprint, render_template, request

from flask import redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField, EmailField, SubmitField
from wtforms.validators import DataRequired, Email, Length

from .models import User

bp = Blueprint('main', __name__)

@bp.route('/')
def home():
    # 将 title 和 name 变量传递给模板
    return render_template('index.html', title = "Flask 模板", name = "Linxq")


# 模板继承
@bp.route("/index2")
def index2():
    # http://127.0.0.1:5000/index2?user=weetgo
    user = request.args.get("user")
    return render_template('index2.tpl', user= user)

# 表单处理
@bp.route("/form")
def form():
    return render_template('form.tpl')
# 表单提交要指定方法
@bp.route('/submit', methods=['POST']) # TODO: 这里路由不能是 “/form/submit”，会找不到
def submit():
    name = request.form.get('name')
    email = request.form.get('email')
    return f'姓名：{name}，邮件：{email}'

# Flask-WTF 和 WTForms 提供了丰富的表单验证功能
class MyForm(FlaskForm):
    name = StringField('姓名：', validators=[DataRequired(), Length(min=1, max=50)])
    email = EmailField('邮件：', validators=[DataRequired(), Email()])
    submit = SubmitField('提交')

@bp.route('/wtf', methods=['POST', 'GET'])
def wtfform():
    form = MyForm()
    # 从 WTForms 2.3.0开始，电子邮件验证器 Email() 由email-validator的外部库处理
    # >pip install email-validator
    if form.validate_on_submit():
        name = form.name.data
        email = form.email.data

        User.add(name, email)

        return f'姓名：{name}，邮件：{email}'

    return render_template('wtfform.tpl', form=form)

@bp.route('/upload')
def upload():
    return render_template('upload.html')

# 这里的路由 /upload_file 要与文件上传form中的action一致
@bp.route('/upload_file', methods=['POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files.get('file')
        if file:
            filename = file.filename
            file.save(f'uploads/{filename}')
            return f'文件成功上传：{filename}'
    else:    
        return redirect(url_for('upload'))

# 查询所有用户
@bp.route('/users')
def get_users():
    users = User.get_all()
    # return '<br>'.join([f'{user.name} ({user.email})' for user in users])
    return render_template('users.tpl', users=users)

